/*
        AClientServer - Processing for Android Client/Server Library

        Copyright (c) 2012 Marlon J. Manrique
        
        http://www.marlonj.com

        This library is free software; you can redistribute it and/or
        modify it under the terms of the GNU Lesser General Public
        License as published by the Free Software Foundation; either
        version 2.1 of the License, or (at your option) any later version.

        This library is distributed in the hope that it will be useful,
        but WITHOUT ANY WARRANTY; without even the implied warranty of
        MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
        Lesser General Public License for more details.

        You should have received a copy of the GNU Lesser General
        Public License along with this library; if not, write to the
        Free Software Foundation, Inc., 59 Temple Place, Suite 330,
        Boston, MA  02111-1307  USA

	$Id$

*/

package com.marlonj.processing.aclientserver; 

import java.io.DataInputStream;
import java.io.DataOutputStream;

/**
 * A client of a service. 
 * 
 * Can be use to read and write data from a connection
 */
public class AClient {

	/**
	 * The connection with the service
	 */
	private AConnection connection; 

	/**
	 * Read data from the input stream
	 */
	private DataInputStream dis; 

	/**
	 * Write data from the output stream
	 */
	private DataOutputStream dos; 

	/**
	 * Create a client using the connection with the service 
	 * 
	 * @param connection Connection with the service 
	 */
	public AClient(AConnection connection) {
		// Store the connection to close when necessary
		this.connection = connection;
	}

	/**
	 * Returns the connection associated with the client 
	 * 
	 * @param connection associate with the client 
	 */
	public AConnection getConnection() {
		return connection;
	}

	/**
	 * Open the connection with the service 
	 */
	public void connect() {
		try {
			// Open the connection 
			connection.connect();

			// Convert connections streams in data stream to read 
			// different types of data 
			dis = new DataInputStream(connection.getInputStream());
			dos = new DataOutputStream(connection.getOutputStream());
		} catch(Exception e) {	
			e.printStackTrace();
		}
	}

	/**
	 * Returns a byte read from the connection 
	 *
	 * @param byte receive 
	 */
	public int read() {
		// Try to read the byte 
		try {
			return dis.read();
		} catch(Exception e) {
			e.printStackTrace();
		}

		// Return -1 if some error 
		return -1; 
	}

	/**
	 * Write a byte 
	 * 
	 * @param b data to send 
	 */
	public void write(int b) {
		try {
			dos.write(b);
		} catch(Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Close the connection with the service 
	 */
	public void close() {
		try {
			dos.close();
			dis.close();
			connection.close();
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
}
